package com.client.qiuqiu;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.client.qiuqiu.crypto.RSA;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class FileService extends Service {
    File cryptoFile;
    File downloadFile;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //文件接收服务
    @Override
    public void onCreate() {
        super.onCreate();
        FileService.Connect_Thread Connect_thread = new FileService.Connect_Thread();
        Connect_thread.start();

        //创建文件夹
        //newFile(path,fileName);
        cryptoFile = getExternalFilesDir("crypto");
        downloadFile = getExternalFilesDir("download");

        //记录路径
        User user = ((User)getApplicationContext());
        user.setCryptoFile(cryptoFile);
        user.setDownloadFile(downloadFile);
        //开始接收文件

    }

    class Connect_Thread extends Thread{
        public void run(){
            while (true) {
                User user = ((User) getApplicationContext());
                //在服务端ipconfig，拿到ip填入
                SocketAddress addr = new InetSocketAddress(user.serverIP, 80);
                Socket fileReceiveSocket = new Socket();
                {
                    try {
                        fileReceiveSocket.connect(addr, 1000);
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.exit(0);
                    }
                }

                //获取服务器端的输出流
                PrintStream printStream = null;
                try {
                    printStream = new PrintStream(fileReceiveSocket.getOutputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //发送socket类型
                //客户端与服务器通讯socket
                printStream.println("3");
                printStream.println(user.getId());
                //获取输入流
                Scanner scanner = null;
                try {
                    scanner = new Scanner(fileReceiveSocket.getInputStream());

                    //接收文件的标志
                    //有信息发来继续，否则拥堵在if判断
                    if (scanner.hasNextLine()) {
                        //Log.e("QAQ", "aaaaaaa");
                        String senderID = scanner.nextLine();
                        //File directory = new File(user.getCryptoFile().toString());

                        DataInputStream dataInputStream = new DataInputStream(fileReceiveSocket.getInputStream());
                        PrintStream serverPrintStream = new PrintStream(fileReceiveSocket.getOutputStream());

                        serverPrintStream.println("Ready");
                        String fileName = scanner.nextLine();
                        long fileLength = dataInputStream.readLong();

                        File file = new File(user.getCryptoFile().toString() + File.separatorChar + fileName);
                        FileOutputStream fileOutputStream = new FileOutputStream(file);

                        // 开始接收文件
                        byte[] bytes = new byte[1024];
                        int length = 0;


                        serverPrintStream.println("Ready");
                        while((length = dataInputStream.read(bytes, 0, bytes.length)) != -1) {
                            fileOutputStream.write(bytes, 0, length);
                            fileOutputStream.flush();
                            if(fileOutputStream.getChannel().size() == fileLength){
                                break;
                            }
                        }

                        //接收完成
                        //关闭流
                        fileOutputStream.close();
                        dataInputStream.close();
                        fileReceiveSocket.close();

                        //解密
                        String address2 = user.getCryptoFile().toString() + File.separatorChar + fileName;//加密时的输出地址
                        String address3 = user.getDownloadFile().toString() + File.separatorChar + fileName;//解密时输出地址

                        RSA rsa = new RSA(23, 47);//两个质数(请确保是质数)
                        try {
                            rsa.decryption(address2, address3);//解密
                        } catch (Exception e) {
                            Log.e("Error", String.valueOf(e));
                        }

                        //接收，解码步骤完成
                        //添加接收文件消息
                        Chatmessage chatmessage = new Chatmessage();
                        chatmessage.setSenderID(senderID);
                        chatmessage.setReceiverID(user.getId());
                        chatmessage.setMessage("Received file:" + "\n" + fileName);
                        chatmessage.setDateObject(new Date());
                        if(user.getChatMessagesBox().get(senderID) == null){
                            //之前无消息
                            List<Chatmessage> chatmessages = new ArrayList<>();
                            chatmessages.add(chatmessage);
                            user.getChatMessagesBox().put(senderID, chatmessages);
                        }else {
                            //有消息
                            List<Chatmessage> chatmessages = user.getChatMessagesBox().get(senderID);
                            chatmessages.add(chatmessage);
                            user.getChatMessagesBox().put(senderID, chatmessages);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //
            }
        }
    }

    class receiveFile_Thread extends Thread{
        public void run(){
            User user = ((User)getApplicationContext());
            Socket fileSocket = user.getFileSocket();

            //获取输入流
            Scanner scanner = null;
            try {
                scanner = new Scanner(fileSocket.getInputStream());

                //接收文件的标志
                while (scanner.hasNextLine()){
                    Log.e("QAQ","aaaaaaa");
                    String msg = scanner.nextLine();
                    //File directory = new File(user.getCryptoFile().toString());

                    DataInputStream dataInputStream = new DataInputStream(user.getFileSocket().getInputStream());


                    String fileName = dataInputStream.readUTF();
                    long fileLength = dataInputStream.readLong();

                    File file = new File(user.getCryptoFile().toString() + File.separatorChar + fileName);
                    FileOutputStream fileOutputStream = new FileOutputStream(file);

                    // 开始接收文件
                    byte[] bytes = new byte[1024];
                    int length = 0;
                    while(true) {
                        if(dataInputStream.readChar() == '0'){
                            break;
                        }
                        length = dataInputStream.read(bytes, 0, bytes.length);
                        fileOutputStream.write(bytes, 0, length);
                        fileOutputStream.flush();
                    }
                    //接收完成

                    //解密
                    String address2 = user.getCryptoFile().toString() + File.separatorChar + fileName;//加密时的输出地址
                    String address3 = user.getDownloadFile().toString() + File.separatorChar + fileName;//解密时输出地址

                    RSA rsa = new RSA(23,47);//两个质数(请确保是质数)
                    try {
                        rsa.decryption(address2, address3);//解密
                    } catch (Exception e) {
                        Log.e("Error", String.valueOf(e));
                    }
                }

            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
